package com.clouddot.baipai.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerIAlaunchActivityComponent;
import com.clouddot.baipai.contract.IAlaunchActivityContract;
import com.clouddot.baipai.http.entity.response.getBanPaiModelResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.environment;
import com.clouddot.baipai.module.AlaunchActivityModule;
import com.clouddot.baipai.ui.service.MyService;
import com.clouddot.baipai.util.ThreadPool.ThreadPoolFactory;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.ViewAnim;
import com.clouddot.baipai.util.viewUtil.getTimeAndWeatherUtil;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseActivity;

import java.util.Calendar;

import javax.inject.Inject;

import butterknife.BindView;

import static com.clouddot.baipai.util.viewUtil.netConnectUtil.isNetworkConnected;

/**
 * Created by wxy on 2018/05/27.
 *
 * @author wxy
 * @date on 2018/05/27 11:32
 * 加载页面，主要是用来判断网络，班牌模式，和初始化定时开关机
 */

public class AlaunchActivity extends BaseActivity implements IAlaunchActivityContract.IView {
    private int currentFlag; //currentFlag == 0 标识service 第一次启动，注入定时开关机的闹钟进去

    @Inject
    IAlaunchActivityContract.IPresenter mPresenter;
    @BindView(R.id.loading)
    ImageView loading;

    @Override
    protected int getContentViewId() {
        return R.layout.h_activity_launch;
    }

    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected void initVariables() {
        DaggerIAlaunchActivityComponent.builder().alaunchActivityModule(new AlaunchActivityModule(this)).build().inject(this);

        /**
         * 判断当前的service是否已经启动
         */
        if (!getTimeAndWeatherUtil.isServiceRunning(this, "com.clouddot.newbanpai.ui.service.MyService")) {
            Intent sIntent = new Intent(this, MyService.class);
            startService(sIntent);
            currentFlag = 0;
        } else {
            currentFlag = 1;
        }
    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        ThreadPoolFactory.getThread().execute(new Runnable() {
//            @Override
//            public void run() {
//                checkNet();
//            }
//        });
//    }


    @Override
    protected void initViews() {
        Animation loadingAnim = ViewAnim.getRotateImg(this);
        loading.startAnimation(loadingAnim);
        ThreadPoolFactory.getThread().execute(new Runnable() {
            @Override
            public void run() {
                checkNet();
            }
        });
        int uiFlags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
    }

    @Override
    protected void loadData() {
    }

    @Override
    public void success(int flag, Object object) {
        Handler handler = new Handler();

        if (flag == 0) {
            /**服务第一次启动，定时开关机注入到机器*/
            setTimeToStartBanPai(object);
        }
        if (Env.getAppContext().banPaiType == 0) {

            handler.postDelayed(new ComeTo1920(object), 1500);

        } else if (Env.getAppContext().banPaiType == 1) {

            handler.postDelayed(new ComeTo751(object), 1500);
        }
    }

    @Override
    public void fail(int flag, String errMsg) {
        ToastUtil.showToast(AlaunchActivity.this, "获取班牌模式失败，正在重新获取...");
        Intent intent = new Intent(AlaunchActivity.this, SettingActivity.class);
        startActivityForResult(intent, 1);
    }

    /***
     * 网络检测
     */
    private void checkNet() {
        int i = 0;
        while (true) {
            try {
                //判断网络是否可用和是否初始化成功
                if (isNetworkConnected(this) && Env.getAppContext().isInitial) {
                    mPresenter.getBanPaiModel(currentFlag);
                    break;
                }
                if (i == 3) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            CometTosetting();
                        }
                    });
                    break;
                }
                Thread.sleep(1000);
                i++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 跳到横屏
     * 请求BanPai模式返回的response对象
     */
    private class ComeTo1920 implements Runnable {
        getBanPaiModelResponse response;

        private ComeTo1920(Object object) {
            response = (getBanPaiModelResponse) object;
        }

        @Override
        public void run() {
            if (response.Model.equals("Common")) {
                if (response.CardReadType.equals("Serial")) {
                    Env.getAppContext().SerialPath = response.DevicePath.isEmpty() ? "/dev/ttyS3" : response.DevicePath;
                    ActivityJump(H_SMainActivity.class);
                } else if (response.CardReadType.equals("Usb")) {
                    ActivityJump(H_UMainActivity.class);
                } else {
                    TipDialog("初始化错误", "读卡类型为空，请到后台去配置班牌的读卡类型");
                }
            } else if (response.Model.equals("Urgent")) {
                ActivityJump(UrgentActivity.class);
            } else if (response.Model.equals("Shutdown")) {
                if (response.CardReadType.equals("Serial")) {
                    Intent intent = new Intent("android.intent.action.shutdown");
                    sendBroadcast(intent);
                } else {
                    try {
                        Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});  //关机
                        proc.waitFor();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (response.Model.equals("Reboot")) {
                if (response.CardReadType.equals("Serial")) {
                    Intent intent = new Intent("android.intent.action.reboot");
                    sendBroadcast(intent);
                } else {
                    try {
                        Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot "}); //重启
                        proc.waitFor();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            } else {
                TipDialog("初始化错误", "班牌模式未初始化，请到后台进行初始化");
            }
        }
    }

    /**
     * 跳到竖屏
     * 请求BanPai模式返回的response对象
     */

    private class ComeTo751 implements Runnable {
        getBanPaiModelResponse response;

        private ComeTo751(Object object) {
            response = (getBanPaiModelResponse) object;
        }

        @Override
        public void run() {
            if (response.Model.equals("Common")) {
                Env.getAppContext().SerialPath = response.DevicePath.isEmpty() ? "/dev/ttyS1" : response.DevicePath;
                ActivityJump(V_SMainActivity.class);

            } else if (response.Model.equals("Urgent")) {
                ActivityJump(UrgentActivity.class);

            } else if (response.Model.equals("Shutdown")) {
                try {
                    Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});  //关机
                    proc.waitFor();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (response.Model.equals("Reboot")) {
                try {
                    Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot "}); //重启
                    proc.waitFor();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                TipDialog("初始化错误", "班牌模式未初始化，请到后台进行初始化");
            }
        }
    }


    /**
     * 没网络或者没有IP地址提示
     */
    private void CometTosetting() {
        //Todo 网络提示跳到设置界面
        String title;
        String content;
        final int type;
        if (!Env.getAppContext().isInitial) {
            title = "IP地址检测结果";
            content = "当前IP地址为空，请到设置界面设置 IP 地址";
            type = 0;
        } else {
            title = "网络检测结果";
            content = "当前的网络不可用，请到系统设置连接网络";
            type = 1;
        }
        new MaterialDialog.Builder(AlaunchActivity.this)
                .title(title)
                .content(content)
                .positiveText("同意")
                .negativeText("重新检测")
                .cancelable(false)
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            if (type == 0) {
                                Intent intent = new Intent(AlaunchActivity.this, SettingActivity.class);
                                startActivityForResult(intent, 1);
                            } else {
                                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                startActivityForResult(intent, 1);
                            }
                        } else if (which == DialogAction.NEGATIVE) {
                            ThreadPoolFactory.getThread().execute(new Runnable() {
                                @Override
                                public void run() {
                                    checkNet();
                                }
                            });
                        }
                    }
                }).show();
    }

    /**
     * 定时开关机
     *
     * @param object 请求BanPai模式返回的response对象
     */
    private void setTimeToStartBanPai(Object object) {
        getBanPaiModelResponse response = (getBanPaiModelResponse) object;
        String[] startTime = response.ChooseStartMechine.contains(":") ? response.ChooseStartMechine.split(":") : "7:00".split(":");
        String[] endTime = response.ChooseShutdownMechine.contains(":") ? response.ChooseShutdownMechine.split(":") : "19:00".split(":");
        if (Env.getAppContext().banPaiType == 0) {
            if (response.CardReadType.equals("Serial")) {
                Calendar c = Calendar.getInstance();
                int mYear = c.get(Calendar.YEAR);
                int mMonth = c.get(Calendar.MONTH) + 1;
                int mDay = c.get(Calendar.DAY_OF_MONTH);
                Intent intent = new Intent("android.intent.action.setpoweronoff");
                int[] timeon = new int[]{mYear, mMonth, mDay, Integer.parseInt(startTime[0]), Integer.parseInt(startTime[1]), 0}; //开机时间
                intent.putExtra("timeon", timeon);
                int[] timeoff = new int[]{mYear, mMonth, mDay, Integer.parseInt(endTime[0]), Integer.parseInt(endTime[1]), 0}; //关机时间
                intent.putExtra("timeoff", timeoff);
                intent.putExtra("enable", true);
                sendBroadcast(intent);
            }
        } else {
            Intent clearIntent = new Intent("android.intent.action.DELETE_ALARM_BY_SERVER");
            clearIntent.putExtra("delete_all", true);
            sendOrderedBroadcast(clearIntent, null);

            Intent end = new Intent("android.intent.action.ADD_ALARM_BY_SERVER");
            end.putExtra("hour", Integer.parseInt(endTime[0]));
            end.putExtra("minute", Integer.parseInt(endTime[1]));
            end.putExtra("mAttribute", 2);
            end.putExtra("daysOfWeek", 0x7f);
            sendOrderedBroadcast(end, null);

            Intent start = new Intent("android.intent.action.ADD_ALARM_BY_SERVER");
            start.putExtra("hour", Integer.parseInt(startTime[0]));
            start.putExtra("minute", Integer.parseInt(startTime[1]));
            start.putExtra("mAttribute", 1);
            start.putExtra("daysOfWeek", 0x7f);
            sendOrderedBroadcast(start, null);
        }

        currentFlag = 1; /**定时已注入*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            ThreadPoolFactory.getThread().execute(new Runnable() {
                @Override
                public void run() {
                    checkNet();
                }
            });
        }
    }

    private void TipDialog(String title, String content) {
        new MaterialDialog.Builder(AlaunchActivity.this).title(title).content(content).positiveText("同意").cancelable(false)
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            for (Activity activity : environment.getInstance().activities) {
                                activity.finish();
                            }
                            environment.getInstance().activities.clear();
                        }
                    }
                })
                .show();
    }

    private void ActivityJump(Class cls) {
        startActivity(new Intent(AlaunchActivity.this, cls));
        this.finish();
    }
}
